﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore.Storage;

namespace ESoft.DataAccess.EfCore
{
    /// <summary>
    /// 事务管理器
    /// </summary>
    public sealed class DbTransaction : ITransaction
    {

        private bool _alreadyDisposed = false;
        private readonly IDbContextTransaction _transaction;

        /// <summary>
        /// 
        /// </summary>
        public Guid TransactionId => _transaction.TransactionId;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="transaction"></param>
        public DbTransaction(IDbContextTransaction transaction)
        {
            _transaction = transaction;
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void CommitTransaction()
        {
            _transaction.Commit();
        }

        public void Dispose()
        {
            //必须为true
            this.Dispose(true);

            //通知垃圾回收机制不再调用终结器（析构器）
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool isDisposing)
        {
            // Don't dispose more than once. 
            if (_alreadyDisposed)
                return;
            if (isDisposing)
            {
                // elided: free managed resources here. 
                _transaction.Dispose();
            }
            // elided: free unmanaged resources here. 
            // Set disposed flag: 
            _alreadyDisposed = true;
        }

        public void RollbackTransaction()
        {
            _transaction.Rollback();
        }
    }
}
